/**
 * @description: 定义班级 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide } from '@midwayjs/core';
import { RobotWebapiRecords } from './robot_webapi_records.entity';

import { InjectRepository, InjectDataSource } from '@midwayjs/sequelize';
import { Repository, Sequelize } from 'sequelize-typescript';

@Provide()
export class RobotWebapiRecordsModel {

  @InjectRepository(RobotWebapiRecords)
  RobotWebapiRecordsRepository: Repository<RobotWebapiRecords>;

  @InjectDataSource()
  SequelizeQuery: Sequelize;

  /**
     * 分页查询获取总条数
     * @param {*} params 
     * @returns 
     */
  async getTotalNum(params: any): Promise<any> {
    // let sql = `SELECT count(1) as num from robot_webapi_records WHERE webapi_name LIKE '%${searchKey}%' OR created_username LIKE '%${searchKey}%';`;
    const { pageNum = 1, pageSize = 10, ...reset } = params;
    let str = "";
    if (Object.keys(reset).length) {
      str = "WHERE ";
      for (let key in reset) {
        switch (key) {
          case "searchKey":
            str += `( webapi_name LIKE '%${reset[key]}%' OR webapi_username LIKE '%${reset[key]}%') AND `
            break;
          case "webapiStatus":
            str += `webapi_status = '${reset[key]}' AND `
            break;
          case "testingStatus":
            str += `testing_status = ${reset[key]} AND `
            break;
          case "filterDateType":
            str += `DATE_FORMAT(${reset[key]},'%Y-%m-%d') >= '${reset['filterDate'][0]}' AND DATE_FORMAT(${reset[key]},'%Y-%m-%d') <= '${reset['filterDate'][1]}' AND `
            break;
          default:
            break;
        }
      }
      str = str.substring(0, str.lastIndexOf('AND '))
    }
    const sql = `SELECT count(1) as num from robot_webapi_records ${str};`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 分页查询获取列表
   * @param {*} pageNum 
   * @param {*} pageSize
   * @param {*} searchKey
   * @returns 
   */
  async getDataByPage(params: any): Promise<any> {
    const { pageNum = 1, pageSize = 10, ...reset } = params;
    const _limit = (pageNum - 1) * pageSize;
    let str = "";
    if (Object.keys(reset).length) {
      str = "WHERE ";
      for (let key in reset) {
        switch (key) {
          case "searchKey":
            str += `( webapi_name LIKE '%${reset[key]}%' OR webapi_username LIKE '%${reset[key]}%') AND `
            break;
          case "webapiStatus":
            str += `webapi_status = '${reset[key]}' AND `
            break;
          case "testingStatus":
            str += `testing_status = ${reset[key]} AND `
            break;
          case "filterDateType":
            str += `DATE_FORMAT(${reset[key]},'%Y-%m-%d') >= '${reset['filterDate'][0]}' AND DATE_FORMAT(${reset[key]},'%Y-%m-%d') <= '${reset['filterDate'][1]}' AND `
            break;
          default:
            break;
        }
      }
      str = str.substring(0, str.lastIndexOf('AND '))
    }
    const sql = `SELECT * from robot_webapi_records ${str} ORDER BY created_at DESC LIMIT ${_limit},${pageSize};`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 新增任务通知
   * @param {*} webapiName 
   * @param {*} webapiContent 
   * @param {*} webapiType
   * @param {*} webapiEndtime 
   * @param {*} webapiStatus 
   * @param {*} webapiUserid 
   * @param {*} webapiUsername 
   * @param {*} webapiConfig
   * @param {*} brandId
   * @param {*} brandName
   * @param {*} projectId
   * @param {*} projectName
   * @param {*} testingInterval
   * @param {*} sendSuccessMsg
   * @param {*} webapiMethod
   * @param {*} webapiDomain
   * @param {*} webapiPath
   * @param {*} webapiData
   * @param {*} webapiCheck
   * @param {*} createdUserid
   * @param {*} createdUsername
   * @returns 
   */
  async insertWebapi(params: any): Promise<any> {
    const sql = `INSERT INTO robot_webapi_records 
    SET webapi_name = '${params.webapiName}',
    webapi_content = '${params.webapiContent}',
    webapi_type = '${params.webapiType}',
    webapi_endtime = '${params.webapiEndtime}',
    webapi_status = '${params.webapiStatus}',
    webapi_userid = '${params.webapiUserid}',
    webapi_username = '${params.webapiUsername}',
    webapi_config = '${params.webapiConfig}',
    brand_id = ${params.brandId},
    brand_name = '${params.brandName}',
    project_id = ${params.projectId},
    project_name = '${params.projectName}',
    testing_interval = ${params.testingInterval},
    send_success_msg = ${params.sendSuccessMsg},
    webapi_method = '${params.webapiMethod}',
    webapi_domain = '${params.webapiDomain}',
    webapi_path = '${params.webapiPath}',
    webapi_data = '${params.webapiData}',
    webapi_check = '${params.webapiCheck}',
    created_userid = '${params.createdUserid}',
    created_username = '${params.createdUsername}',
    webapi_class = '${params.webapiClass}',
    created_at = now(),
    updated_at = now();`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 更新任务通知
   * @param {*} id 
   * @param {*} webapiName 
   * @param {*} webapiContent 
   * @param {*} webapiType
   * @param {*} webapiEndtime 
   * @param {*} webapiStatus 
   * @param {*} webapiUserid 
   * @param {*} webapiUsername 
   * @param {*} webapiConfig
   * @param {*} brandId
   * @param {*} brandName
   * @param {*} projectId
   * @param {*} projectName
   * @param {*} testingInterval
   * @param {*} sendSuccessMsg
   * @param {*} webapiMethod
   * @param {*} webapiDomain
   * @param {*} webapiPath
   * @param {*} webapiData
   * @param {*} webapiCheck
   * @returns 
   */
  async updateWebapiById(params: any): Promise<any> {
    let sql = `UPDATE robot_webapi_records 
    SET webapi_name = '${params.webapiName}',
        webapi_content = '${params.webapiContent}',
        webapi_type = '${params.webapiType}',
        webapi_endtime = '${params.webapiEndtime}',
        webapi_status = '${params.webapiStatus}',
        webapi_userid = '${params.webapiUserid}',
        webapi_username = '${params.webapiUsername}',
        webapi_config = '${params.webapiConfig}',
        brand_id = ${params.brandId},
        brand_name = '${params.brandName}',
        project_id = ${params.projectId},
        project_name = '${params.projectName}',
        testing_interval = ${params.testingInterval},
        send_success_msg = ${params.sendSuccessMsg},
        webapi_method = '${params.webapiMethod}',
        webapi_domain = '${params.webapiDomain}',
        webapi_path = '${params.webapiPath}',
        webapi_data = '${params.webapiData}',
        webapi_check = '${params.webapiCheck}',
        webapi_class = '${params.webapiClass}',
        updated_at = now()
    WHERE
        id = ${params.id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 删除任务通知
   * @param {*} id 
   * @returns 
   */
  async delWebapiById(id: number): Promise<any> {
    const sql = `DELETE r,l from robot_webapi_records r left JOIN robot_webapi_logs l ON r.id = l.webapi_id WHERE r.id = ${id};`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
  * 根据项目id查询任务通知
  * @param {*} id
  * @returns 
  */
  async getWebapiById(id: number): Promise<any> {
    const sql = `select * from robot_webapi_records WHERE id = ${id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 修改任务通知状态
   * @param {*} id 
   * @param {*} webapiStatus
   * @returns 
   */
  async updateWebapiStatus(params: any): Promise<any> {
    const sql = `UPDATE robot_webapi_records SET webapi_status = '${params.webapiStatus}' WHERE id = ${params.id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }


  /**
   * 查询任务未进行中的通知消息
   * @param {*} webapiStatus
   * @returns 
   */
  async getDataByStatus(webapiStatus: string): Promise<any> {
    const sql = `SELECT * FROM robot_webapi_records where webapi_status = '${webapiStatus}' ORDER BY created_at DESC;`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 更新当前api最新的测试结果和时间
   * @param {*} id
   * @param {*} testing_time
   * @param {*} testing_status
   * @returns 
   */
  async getTestingById(params: any): Promise<any> {
    const sql = `UPDATE robot_webapi_records SET testing_time = '${params.testingTime}', testing_status = ${params.testingStatus} WHERE id = ${params.id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

}